/**
 * 本模块封装了Android、iOS的应用权限判断、打开应用权限设置界面、以及位置系统服务是否开启
 */

var isIos;
// #ifdef APP-PLUS
isIos = plus.os.name == "iOS";
// #endif

/**
 * 定义了iOS平台所需的各种权限枚举。
 */
enum IOSPermission {
  /**
   * 获取定位权限是否开启
   */
  Location = "Location",
  /**
   * 获取相机权限是否开启
   */
  Camera = "Camera",
  /**
   * 获取相册权限是否开启
   */
  PhotoLibrary = "PhotoLibrary",
  /**
   * 获取录音权限是否开启
   */
  Record = "Record",
  /**
   * 获取推送权限是否开启
   */
  Push = "Push",
  /**
   * 获取通讯录权限是否开启
   */
  Contact = "Contact",
  /**
   * 获取日历权限是否开启
   */
  Calendar = "Calendar",
  /**
   * 获取备忘录权限是否开启
   */
  Memo = "Memo",
}

/**
 * 判断iOS平台是否开启定位权限
 */
const judgeIosPermissionLocation = () => {
  let result = false;
  const cllocationManger = plus.ios.import("CLLocationManager");
  const status = cllocationManger.authorizationStatus();
  result = status != 2;
  console.log("定位权限开启：" + result);
  plus.ios.deleteObject(cllocationManger);
  return result;
};

/**
 * 判断iOS平台是否开启相机权限
 */
const judgeIosPermissionCamera = () => {
  let result = false;
  const AVCaptureDevice = plus.ios.import("AVCaptureDevice");
  const status = AVCaptureDevice.authorizationStatusForMediaType("vide");
  console.log("authStatus:" + status);
  console.log("相机权限开启：" + result);
  if (status == 3) {
    result = true;
    console.log("相机权限已经开启");
  } else {
    console.log("相机权限没有开启");
  }
  plus.ios.deleteObject(AVCaptureDevice);
  return result;
};

/**
 * 判断iOS平台是否开启相册权限
 */
const judgeIosPermissionPhotoLibrary = () => {
  let result = false;
  const PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
  const status = PHPhotoLibrary.authorizationStatus();
  console.log("authorizationStatus:" + status);
  if (status == 3) {
    result = true;
    console.log("相册权限已经开启");
  } else {
    console.log("相册权限没有开启");
  }
  plus.ios.deleteObject(PHPhotoLibrary);
  return result;
};

/**
 * 判断iOS平台是否开启麦克风权限
 */
const judgeIosPermissionRecord = () => {
  let result = false;
  const AVAudioSession = plus.ios.import("AVAudioSession");
  const avAudio = AVAudioSession.sharedInstance();
  const status = avAudio.recordPermission();
  console.log("permissionStatus:" + status);
  if (status == 1684369017 || status == 1970168948) {
    console.log("麦克风权限没有开启");
  } else {
    result = true;
    console.log("麦克风权限已经开启");
  }
  plus.ios.deleteObject(AVAudioSession);
  return result;
};

/**
 * 判断推送权限是否开启
 */
const judgeIosPermissionPush = () => {
  let result = false;
  const UIApplication = plus.ios.import("UIApplication");
  const app = UIApplication.sharedApplication();
  let enabledTypes = 0;
  if (app.currentUserNotificationSettings) {
    var settings = app.currentUserNotificationSettings();
    enabledTypes = settings.plusGetAttribute("types");
    console.log("enabledTypes1:" + enabledTypes);
    if (enabledTypes == 0) {
      console.log("推送权限没有开启");
    } else {
      result = true;
      console.log("已经开启推送功能!");
    }
    plus.ios.deleteObject(settings);
  } else {
    enabledTypes = app.enabledRemoteNotificationTypes();
    if (enabledTypes == 0) {
      console.log("推送权限没有开启!");
    } else {
      result = true;
      console.log("已经开启推送功能!");
    }
    console.log("enabledTypes2:" + enabledTypes);
  }
  plus.ios.deleteObject(app);
  plus.ios.deleteObject(UIApplication);
  return result;
};

/**
 * 判断iOS平台是否开启通讯录权限
 */
const judgeIosPermissionContact = () => {
  let result = false;
  const CNContactStore = plus.ios.import("CNContactStore");
  const status = CNContactStore.authorizationStatusForEntityType(0);
  console.log("status:" + status);
  if (status == 3) {
    result = true;
    console.log("通讯录权限已经开启");
  } else {
    console.log("通讯录权限没有开启");
  }
  plus.ios.deleteObject(CNContactStore);
  return result;
};

/**
 * 判断iOS平台是否开启日历权限
 */
const judgeIosPermissionCalendar = () => {
  let result = false;
  const EKEventStore = plus.ios.import("EKEventStore");
  const status = EKEventStore.authorizationStatusForEntityType(0);
  console.log("status:" + status);
  if (status == 3) {
    result = true;
    console.log("日历权限已经开启");
  } else {
    console.log("日历权限没有开启");
  }
  plus.ios.deleteObject(EKEventStore);
  return result;
};

/**
 * 判断iOS平台是否开启备忘录权限
 */
const judgeIosPermissionMemo = () => {
  let result = false;
  const EKEventStore = plus.ios.import("EKEventStore");
  const status = EKEventStore.authorizationStatusForEntityType(1);
  console.log("status:" + status);
  if (status == 3) {
    result = true;
    console.log("备忘录权限已经开启");
  } else {
    console.log("备忘录权限没有开启");
  }
  plus.ios.deleteObject(EKEventStore);
  return result;
};

/**
 * 判断iOS平台权限
 * @param IOSPermission
 * @returns
 */
const requestIosPermission = (IOSPermission: IOSPermission): boolean => {
  if (IOSPermission == "Location") {
    return judgeIosPermissionLocation();
  } else if (IOSPermission == "Camera") {
    return judgeIosPermissionCamera();
  } else if (IOSPermission == "PhotoLibrary") {
    return judgeIosPermissionPhotoLibrary();
  } else if (IOSPermission == "Record") {
    return judgeIosPermissionRecord();
  } else if (IOSPermission == "Push") {
    return judgeIosPermissionPush();
  } else if (IOSPermission == "Contact") {
    return judgeIosPermissionContact();
  } else if (IOSPermission == "Calendar") {
    return judgeIosPermissionCalendar();
  } else if (IOSPermission == "Memo") {
    return judgeIosPermissionMemo();
  }
  console.log("没有找到对应的权限");
  return false;
};

/* -------------------------------------------------  安卓权限判断 ------------------------------------------------- */

interface RequestPermissionsResult {
  code?: number;
  message?: string;
}
/**
 * 定义了Android平台所需的各种权限枚举。
 * 这些权限常量用于精确指定在请求权限时需要哪一项权限。
 */
enum AndroidPermission {
  /**
   * 获取精确的位置权限。
   */
  ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION",

  /**
   * 获取模糊位置权限，通常用于蓝牙或BLE相关的功能。
   */
  ACCESS_COARSE_LOCATION = "android.permission.ACCESS_COARSE_LOCATION",

  /**
   * 访问摄像头的权限。
   */
  CAMERA = "android.permission.CAMERA",

  /**
   * 读取外部存储（包括相册）的权限。
   */
  READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE",

  /**
   * 写入外部存储（包括相册）的权限。
   */
  WRITE_EXTERNAL_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE",

  /**
   * 录音权限，即访问麦克风。
   */
  RECORD_AUDIO = "android.permission.RECORD_AUDIO",

  /**
   * 读取通讯录的权限。
   */
  READ_CONTACTS = "android.permission.READ_CONTACTS",

  /**
   * 写入通讯录的权限。
   */
  WRITE_CONTACTS = "android.permission.WRITE_CONTACTS",

  /**
   * 读取日历的权限。
   */
  READ_CALENDAR = "android.permission.READ_CALENDAR",

  /**
   * 写入日历的权限。
   */
  WRITE_CALENDAR = "android.permission.WRITE_CALENDAR",

  /**
   * 读取短信的权限。
   */
  READ_SMS = "android.permission.READ_SMS",

  /**
   * 发送短信的权限。
   */
  SEND_SMS = "android.permission.SEND_SMS",

  /**
   * 接收新短信的权限。
   */
  RECEIVE_SMS = "android.permission.RECEIVE_SMS",

  /**
   * 获取手机状态信息的权限，如IMEI等。
   */
  READ_PHONE_STATE = "android.permission.READ_PHONE_STATE",

  /**
   * 直接拨打电话的权限。
   */
  CALL_PHONE = "android.permission.CALL_PHONE",

  /**
   * 读取通话记录的权限。
   */
  READ_CALL_LOG = "android.permission.READ_CALL_LOG",
}

/**
 * Android平台权限状态
 */
enum AndroidAppPermissionStatus {
  granted = 0, // 未同意授权
  denied = 1, // 同意授权
  disabled = -1, // 永久拒绝
}

/**
 * 查询安卓端的权限状态。
 */

/**
 * 请求Android应用的权限。
 *
 * @param permissionId 需要请求的权限标识，属于AndroidPermission枚举类型。
 * @returns 返回一个Promise，解决为权限状态（granted、denied、disabled）或者错误信息。
 */
const requestAndroidPermission = (
  permissionId: AndroidPermission
): Promise<AndroidAppPermissionStatus | RequestPermissionsResult> => {
  return new Promise((resolve, reject) => {
    plus.android.requestPermissions(
      [permissionId],
      (res) => {
        // 当权限请求结果返回时的回调函数
        let status = AndroidAppPermissionStatus.granted;

        // 遍历已获取的权限，并设置状态为denied，意味着只要有任一权限被拒绝，则整体状态为denied
        for (var i = 0; i < res.granted.length; i++) {
          var grantedPermission = res.granted[i];
          console.log("已获取的权限：" + grantedPermission);
          status = AndroidAppPermissionStatus.denied;
        }

        // 遍历被拒绝的权限，如果存在被拒绝的权限，则设置状态为granted，意味着只要有一项权限被同意，则整体状态为granted
        for (var i = 0; i < res.deniedPresent.length; i++) {
          var deniedPresentPermission = res.deniedPresent[i];
          console.log("拒绝本次申请的权限：" + deniedPresentPermission);
          status = AndroidAppPermissionStatus.granted;
        }

        // 遍历永久拒绝的权限，并设置状态为disabled
        for (var i = 0; i < res.deniedAlways.length; i++) {
          var deniedAlwaysPermission = res.deniedAlways[i];
          console.log("永久拒绝申请的权限：" + deniedAlwaysPermission);
          status = AndroidAppPermissionStatus.disabled;
        }

        resolve(status); // 返回权限请求的状态
      },
      (error) => {
        // 当权限请求出现错误时的回调函数
        console.log("申请权限错误：" + error.code + " = " + error.message);
        reject({
          code: error.code,
          message: error.message,
        }); // 返回错误信息
      }
    );
  });
};

/* -------------------------------------------------  公共函数 ------------------------------------------------- */
// 跳转到**应用**的权限页面
const gotoAppPermissionSetting = () => {
  if (isIos) {
    const UIApplication = plus.ios.import("UIApplication");
    const application = UIApplication.sharedApplication();
    const NSURL = plus.ios.import("NSURL");
    const setting = NSURL.URLWithString("app-settings:");
    application.openURL(setting);
    plus.ios.deleteObject(application);
    plus.ios.deleteObject(NSURL);
    plus.ios.deletObject(setting);
  } else {
    const Intent = plus.android.importClass("android.content.Intent");
    const Settings = plus.android.importClass("android.provider.Settings");
    const Uri = plus.android.importClass("android.net.Uri");
    const mainActivity = plus.android.runtimeMainActivity();
    const Intent = new Intent();
    Intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    const uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
    intent.setData(uri);
    mainActivity.startActivity(intent);
  }
};

/**
 * checkSystemEnableLocation
 * @returns boolean
 */
const checkSystemEnableLocation = () => {
  if (isIos) {
    const cllocationManger = plus.ios.import("CLLocationManager");
    const result = cllocationManger.locationServicesEnabled();
    console.log("系统定位开启:" + result);
    plus.ios.deleteObject(cllocationManger);
    return result;
  } else {
    const context = plus.android.importClass("android.content.Context");
    const locationManager = plus.android.importClass(
      "android.location.LocationManager"
    );
    const main = plus.android.runtimeMainActivity();
    const mainSvr = main.getSystemService(context.LOCATION_SERVICE);
    const result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
    console.log("系统定位开启:" + result);
    return result;
  }
};

export {
  requestAndroidPermission, // 请求Android应用的权限。
  requestIosPermission, // 请求iOS应用的权限。
  checkSystemEnableLocation, // 检查系统是否开启定位。
  gotoAppPermissionSetting, // 跳转到**应用**的权限页面。
};
